package com.example.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

@RestController
@RequestMapping("/upload")
@CrossOrigin(allowCredentials = "true")
public class FilesUploadController {

    @Value("${prop.upload-folder}")
    private String UPLOAD_FOLDER;
    private Logger logger = LoggerFactory.getLogger(FilesUploadController.class);

    @PostMapping(value = "/singleFile")
    public Object singleFileUpload(MultipartFile file) throws IOException {
        logger.info("传入的文件参数: {}", file.getOriginalFilename());
        if(Objects.isNull(file) || file.isEmpty()){
            logger.error("文件为空");
            return "文件为空,请重新上传";
        }

        try{
            File directory = new File(".");
            logger.info("directory: {}",directory.getCanonicalPath());
            String filePath = directory.getCanonicalPath()+"\\"+UPLOAD_FOLDER+file.getOriginalFilename();
            logger.info(filePath);
            File file1 = new File(filePath);
            logger.info("file1.getPath: {}",file1.getPath());
            logger.info("file1.getName: {}",file1.getName());
            if(!file1.getParentFile().exists()){
                file1.getParentFile().mkdir();
            }
            file.transferTo(file1);
            logger.debug("文件写入成功");
            return "done";
        }catch (IOException e){
            e.printStackTrace();
            return "error";
        }

    }
}
